package org.hot100_0.leetcode347;

import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.PriorityQueue;

public class Solution {
    public int[] topKFrequent(int[] nums, int k) {

        HashMap<Integer,Integer> hashMap = new HashMap<>();

        for (int num :nums ) {
            if (hashMap.containsKey(num)){
                Integer times = hashMap.get(num);
                times++;
                hashMap.put(num,times);
            }else {
                hashMap.put(num,1);
            }
        }


        PriorityQueue<Map.Entry<Integer,Integer>> priorityQueue =
                new PriorityQueue<>((entry1,entry2)->entry1.getValue()-entry2.getValue());

        for (Map.Entry<Integer,Integer> entry:hashMap.entrySet()) {
            if (priorityQueue.size()<k){
                priorityQueue.add(entry);
            }else {
                if (entry.getValue()>priorityQueue.peek().getValue()){
                    priorityQueue.add(entry);
                }
                priorityQueue.poll();
            }
        }

        int [] res= new int[k];
        for (int i = 0; i < k; i++) {
            res[i]=priorityQueue.poll().getKey();
        }
        return res;
    }
}
